<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Config;

class ESInit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'es:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'init ElasticSearch index for shop';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //创建template
        $client =   new Client();

        $config  =  Config::get('scout.elasticsearch');
        $post_url=  $config['host'] . '/_template/tmp';
        $params  =   [
            'json'  =>  [
                'template'  =>  $config['index'],
                'mappings'  =>  [
                    '_default'  =>  [
                        'dynamic_templates' =>  [
                            'string_fields'   =>  [
                                'match_mapping_type'    =>  'string',
                                'mapping'   =>  [
                                    'type'  =>  'text',
                                    'analyzer'  =>  'ik_max_word',
                                    'fields'    =>  [
                                        'keyword'   =>  [
                                            'type'  =>  'keyword'
                                        ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ];

        //发送参数
//        $result =   $client->put($post_url, $params['json']);
        $this->info("=========创建模板成功============");

        //创建索引
        $index_url= $config['host'] . '/' . $config['index'];
        $params   = [
            'setting'   =>  [
                'refresh_interval'  =>  '3s',
                'number_of_shards'  =>  1,
                'number_of_replicas'=>  0
            ],
            'mappings'  =>  [
                '_default'  =>  [
                    '_all'  =>  [
                        'enable'    =>  false
                    ],
                ],
            ],
        ];

        //发送参数
        $client->put($index_url, $params);

        $this->info("=======创建索引成功=========");
    }
}
